<script setup lang="ts">

import {buyListApi, delListApi, updateShoppingApi} from "~/api/orderApi";
import {successCode} from "~/api/base/http";
import {getMapList} from "~/api/mapApi";
import MySelect from "~/components/constant/mySelect.vue";
import FormItem from "~/components/constant/formItem.vue";
import {getUserList} from "~/api/userApi";
import CommodityOrder from "~/components/shop/commodityOrder.vue";
import {error, success} from "~/utils/myMessage";


const shoppingShow = defineModel('modelValue');

const props = defineProps({
  title: {
    type: String,
    default: "购物车"
  }
})

onMounted(() => {
  initAddressMapList();
  initUserList();
})

const totalCount = ref(0.00)

function calcTotalCount() {
  totalCount.value = 0.0;
  for (let i = 0; i < checkState.value.length; i++) {
    if (checkState.value[i]) {
      let itemMoney = (userInfoStore().shoppingList && userInfoStore().shoppingList[i].money) ? parseFloat(userInfoStore().shoppingList[i].money) : 0.0;
      totalCount.value = totalCount.value + itemMoney;
    }
  }
  totalCount.value = constantStore().formatNumber(totalCount.value, 2);
}

let checkList = ref([])

function checkClick(obj, index) {
  let state = obj["state"];
  let checkObj = obj["obj"];
  if (state) {
    checkList.value.push(checkObj);
  } else {
    for (let i = 0; i < checkList.value.length; i++) {
      let checkListItem = checkList.value[i];
      if (checkListItem.id === checkObj.id) {
        checkList.value.splice(i, 1);
        break
      }
    }
  }
  checkCheckState();
}

const checkState = ref([])
const checkAll = ref(false)
const isIndeterminate = ref(false)

function checkAllChange() {
  if (checkAll.value) {//全选
    userInfoStore().shoppingList.forEach(item => {
      checkList.value.push(item);
    })
    for (let i = 0; i < checkState.value.length; i++) {
      checkState.value[i] = true;
    }
  } else {//取消全选
    for (let i = 0; i < checkState.value.length; i++) {
      checkState.value[i] = false;
    }
    checkList.value = [];
  }
  isIndeterminate.value = false;
  calcTotalCount();
  // console.log(checkAll.value)
  // console.log(checkList.value)
  // console.log(checkState.value)
}

function delClick(obj, index) {
  let arr = [obj.id]
  delListApi(arr).then(res => {
    if (res.code === successCode) {
      userInfoStore().shoppingList.splice(index, 1);
      delCheckStat(index);
      for (let i = 0; i < checkList.value.length; i++) {
        let item = checkList.value[i];
        if (item.id === obj.id) {
          checkList.value.splice(index, 1);
        }
      }
      success(res.message);
    } else {
      error(res.message);
    }
  })
}

function delShoppingList() {
  let arr = [];
  for (let i = 0; i < checkList.value.length; i++) {
    arr.push(checkList.value[i].id);
  }
  delListApi(arr).then(res => {
    if (res.code === successCode) {
      userInfoStore().initShopping();
      initCheckStat()
      success(res.message);
    } else {
      error(res.message);
    }
  })
}

/**
 * 删除商品选中状态
 * @param index
 */
function delCheckStat(index) {
  for (let i = index; i < checkState.value.length - 1; i++) {
    checkState.value[i] = checkState.value[i + 1]
  }
  checkState.value.splice(checkState.value.length - 1, 1);
  checkCheckState();
}

function checkCheckState() {
  // console.log(checkList.value)
  let isAll = true//全选了
  let isAllNo = true//全没选
  checkState.value.forEach(item => {
    if (item) {
      isAllNo = false;
    } else {
      isAll = false;
    }
  })
  if (!isAll && !isAllNo) {
    isIndeterminate.value = true
  } else {
    isIndeterminate.value = false
  }
  checkAll.value = isAll;
  calcTotalCount();
}

function initCheckStat() {
  checkList.value = [];
  for (let i = 0; i < checkState.value.length; i++) {
    checkState.value[i] = false;
  }
  isIndeterminate.value = false;
  checkAll.value = false;
  totalCount.value = 0.00;
}

function updateClick(obj) {
  updateShoppingApi(obj).then(res => {
    if (res.code === successCode) {
      success(res.message);
      userInfoStore().initShopping();
    } else {
      error(res.message);
    }
  })
  calcTotalCount();
}

function clearShopping() {
  ElMessageBox.alert('您确定要清空购物车吗', '清空购物车提醒', {
    // if you want to disable its autofocus
    // autofocus: false,
    confirmButtonText: 'OK',
    callback: (value) => {
      if ("confirm" === value) {
        let arr = [];
        userInfoStore().shoppingList.forEach(item => {
          arr.push(item.id)
        })
        delListApi(arr).then(res => {
          if (res.code === successCode) {
            userInfoStore().shoppingList = [];
            initCheckStat();
            success(res.message)
          } else {
            error(res.message)
          }
        })
      }
    },
  })
}

let name = ref("");
let projectId = ref("");
let mapType = ref("");
let addressSelect = ref({});

watch(() => constantStore().shoppingThisTabProjectId, (newVal) => {
  initAddressMapList();
})

watch(() => shoppingShow.value, (newVal) => {
  if (newVal) {
    initAddressMapList();
  }
})

function initAddressMapList() {
  if (projectId.value === constantStore().shoppingThisTabProjectId) {
    return;
  }
  projectId.value = constantStore().shoppingThisTabProjectId;//记录上次ID 防止重复访问接口
  getMapList(1, 99999, constantStore().shoppingThisTabProjectId, name.value, mapType.value).then(res => {
    if (res.code === successCode) {
      addressSelect.value = constantStore().listToSelect(res.data.content, "name", "id");
    }
  })
}

let searchObject = ref({
  userKey: "",
  roleId: "",
  powerId: "",
  moneyMin: "",
  moneyMax: "",
  amountMin: "",
  amountMax: ""
})
let userSelect = ref({});

function initUserList() {
  getUserList(1, 99999, searchObject.value).then(res => {
    if (res.code === successCode) {
      userSelect.value = constantStore().listToSelect(res.data.content, "name", "id");
    }
  })
}


let addressShow = ref(false);
let addressId = ref("");
let getUserId = ref("");

function beforeShopping() {
  addressShow.value = true;
}

function cancelShopping() {
  addressId.value = "";
  getUserId.value = "";
}

let buyDoDisable = ref(false);


function doShopping() {
  if (!addressId.value) {
    warning("请选择发货地址")
    return;
  }
  for (let i = 0; i < checkList.value.length; i++) {
    checkList.value[i].addressId = addressId.value;
    if (getUserId.value) {
      checkList.value[i].toUserId = getUserId.value;
    } else {
      checkList.value[i].toUserId = null;
    }
  }
  buyDoDisable.value = true;
  buyListApi(checkList.value).then(res => {
    if (res.code === successCode) {
      success(res.message);
      cancelShopping();
    } else {
      error(res.message);
    }
    initCheckStat();
    checkList.value = []
    buyDoDisable.value = false;
    addressShow.value = false;
    userInfoStore().initShopping();
  })
}
</script>

<template>
  <div class="shopping--box">
    <el-dialog v-model="shoppingShow" :title="props.title" width="500">
      <div class="commodity-button-box">
        <el-checkbox
            v-model="checkAll"
            :indeterminate="isIndeterminate"
            @change="checkAllChange">
          全 选
        </el-checkbox>
      </div>
      <div class="commodity-list-box" v-if="userInfoStore().shoppingList&&userInfoStore().shoppingList.length>0">
        <template v-for="(item, index) in userInfoStore().shoppingList" :key="index">
          <commodity-order :model-value="item" v-model:checkState="checkState[index]"
                           @check="(obj)=>checkClick(obj,index)"
                           @del="(obj)=>delClick(obj,index)" @updateInfo="(obj)=>updateClick(obj,index)"/>
        </template>
      </div>
      <div class="commodity-list-empty" v-else>
        <el-empty description="暂无商品，快去商城选购吧"/>
      </div>
      <template #footer>
        <div class="dialog-footer" style="display: flex; align-items: center;justify-content: space-between">
          <div class="total-money">
            <span style="font-weight: bolder">
            总价：
            </span>
            <span>
            {{ totalCount }}
            </span>
            <span style="font-weight: bolder">
            ￥
            </span>
          </div>
          <div class="footer-button">
            <el-button type="danger" @click="delShoppingList" v-if="checkList.length&&checkList.length>0">
              <el-badge :value="checkList.length" :max="9999999999"
                        :offset="[15, -8]">
                批量删除
              </el-badge>
            </el-button>
            <el-button type="danger" @click="clearShopping"
                       :disabled="!userInfoStore().shoppingList||userInfoStore().shoppingList.length == 0">
              <!--            <el-badge v-if="checkList.length&&checkList.length>0" :value="checkList.length" :max="9999999999"-->
              <!--                      :offset="[15, -8]">-->
              <!--              移 除-->
              <!--            </el-badge>-->
              <!--            <span v-else>-->
              <!--              移 除-->
              <!--            </span>-->
              清 空
            </el-button>
            <el-button type="success" @click="beforeShopping" :disabled="!checkList.length>0">
              <el-badge v-if="checkList.length&&checkList.length>0" :value="checkList.length" :max="9999999999"
                        :offset="[15, -8]">
                付 款
              </el-badge>
              <span v-else>
             付 款
            </span>
            </el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
  <div class="shopping-address-box">
    <el-dialog v-model="addressShow" title="选择收货地址/赠送用户" width="500" @beforeClose="cancelShopping">
      <div class="address-user-box">
        <div class="address-box">
          <form-item title="发货地址" :required="true">
            <my-select v-model="addressId" :option="addressSelect" placeholder="请选择发货地址"/>
          </form-item>
        </div>
        <div class="user-box">
          <form-item title="收件人">
            <my-select v-model="getUserId" :option="userSelect" placeholder="默认收件人是自己"/>
          </form-item>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="doShopping"
                     :disabled="buyDoDisable||(addressId===''||addressId===undefined)" v-loading="buyDoDisable">
            确 定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.shopping--box {
  .commodity-button-box {
    padding: .5rem 1rem;
  }

  .commodity-list-box {
    padding: .5rem 0;
    max-height: 50rem;
    overflow-y: auto; /* 仅垂直滚动 */
    overflow-x: hidden; /* 隐藏水平滚动 */
  }
}

.shopping-address-box {
  .address-user-box {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: start;

    .address-box, .user-box {

    }
  }
}
</style>